package map;

import entity.Player;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.geom.Vector2f;

import entity.Entity;

public class ClientMap extends Map
{
	static String serverMsg = "";
	
	Socket clientSocket;
	String serverIP;
	
	Scanner in;
	DataOutputStream out;
	
	public ClientMap()
	{
		serverIP = "192.168.0.7";
		
		connectToServer();
	}
	
	public void connectToServer()
	{
		try
		{
			clientSocket = new Socket(serverIP, 4446);
			in = new Scanner(clientSocket.getInputStream());
			out = new DataOutputStream(clientSocket.getOutputStream());
			
			ClientConnetion cc = new ClientConnetion(in, out, mapLayers[1]);
			new Thread(cc).start();
			
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void update(GameContainer gc)
	{
		if (!serverMsg.equals("")) 
		{
			Vector2f[] vectors = convertString(serverMsg);
			
			for (Entity currentE : mapLayers[1].entities) 
			{
				{
					if(vectors[0] != null)
						currentE.setPosition(vectors[0]);
					
					if(vectors[1] != null)
						currentE.setSpeed(vectors[1]);
				}
			}
			
			serverMsg = "";
		}
		else
		{
			super.update(gc);
		}
	}
	
	public Vector2f[] convertString(String stringEntity)
	{
		Vector2f [] vectors = new Vector2f[2];
		
		int colenIndex = stringEntity.indexOf(':');
		int startVelocity = stringEntity.indexOf('(');
		int endVelocity = stringEntity.indexOf(')');
		
		float xPos = 0;
		float yPos = 0;
		
		float xSpeed = 0;
		float ySpeed = 0;
		
		if(colenIndex != -1)
		{
			xPos = Float.valueOf(stringEntity.substring(0, colenIndex));
			yPos = Float.valueOf(stringEntity.substring(colenIndex +1, startVelocity));
			
			vectors[0] = new Vector2f(xPos, yPos);
			
			if( startVelocity != -1 || endVelocity != -1)
			{
				colenIndex = stringEntity.indexOf(':', colenIndex + 1);
			
				xSpeed = Float.valueOf(stringEntity.substring(startVelocity + 1, colenIndex));
				xSpeed = Float.valueOf(stringEntity.substring(colenIndex + 1, endVelocity));
			
				vectors[1] = new Vector2f(xSpeed, ySpeed);
			}
		}
		
		return vectors;
	}
}
